-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoggedInController.java
More file actions
38 lines (29 loc) · 1.27 KB
/
LoggedInController.java
File metadata and controls
38 lines (29 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.example.catfactsdaily.controller;
import com.example.catfactsdaily.service.JwtService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
@RestController
@CrossOrigin
@RequestMapping("/logged-in")
@SecurityRequirement(name = "bearerAuth")
public class LoggedInController {
private final JwtService jwtService;
@Autowired
public LoggedInController(JwtService jwtService) {
this.jwtService = jwtService;
}
@PostMapping("/logout")
public ResponseEntity<String> logout(@RequestHeader("Authorization") String token, Principal principal) {
String cleanedToken = token.replace("Bearer ", "");
Integer userIdFromToken = jwtService.extractUserIdFromPrincipal(principal);
if (!jwtService.extractUserId(cleanedToken).equals(userIdFromToken)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized logout attempt.");
}
jwtService.invalidateToken(cleanedToken);
return ResponseEntity.ok("User logged out successfully.");
}
}